package Test;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobActivitiesComInfo;
import weaver.hrm.job.JobGroupsComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: DTY
 * @Date: 2020/8/24
 * @Time: 17:23
 * @Desc: 组织架构同步，从E7同步到E9
 *        需要注意的是所有的表的外键都是id而不是code，在每次同步结束后
 *        要根据原来的id转成code，再到当前E9中转成现在的id
 * @Version: 1.0
 */
public class HrmSynAction {
    private static final String HRMNAME = "HRMNAME";//名称
    private static final String HRMCODE = "HRMCODE";//编码
    private static final String HRMTYPE = "HRMTYPE";//类型
    private static final String HRMSTAUS = "HRMSTAUS";//状态
    private static final String HRMTIME = "HRMTIME";//时间
    private static final String HRMMSG = "HRMMSG";//描述信息
    private static List<Map<String,String>> SubcompanySynMsg = new ArrayList<>();//分部信息集合
    private static List<Map<String,String>> DeptSynMsg = new ArrayList<>();//部门信息集合
    private static List<Map<String,String>> JobGroupSynMsg = new ArrayList<>();//职务类型集合
    private static List<Map<String,String>> JobActivitySynMsg = new ArrayList<>();//职责集合
    private static List<Map<String,String>> JobTitleSynMsg = new ArrayList<>();//岗位集合
    private static List<Map<String,String>> ResourceSynMsg = new ArrayList<>();//人员信息集合
    private static List<Map<String,String>> UpSupsubcomSynMsg = new ArrayList<>();//更新上级分部信息集合
    private static List<Map<String,String>> UpsubcomSynMsg = new ArrayList<>();//更新部门所属分部信息集合
    private static List<Map<String,String>> UpHrmsubcomSynMsg = new ArrayList<>();//更新人员所属分部信息集合
    private static List<Map<String,String>> UpHrmDeptSynMsg = new ArrayList<>();//更新人员所属部门信息集合
    private static List<Map<String,String>> UpdSupDeptSynMsg = new ArrayList<>();//更新上级部门信息集合
    private static List<Map<String,String>> UpGroupidSynMsg = new ArrayList<>();//更新职务类型集合
    /*private static boolean hasSynsubcompany = false;
    private static boolean hasSyndept = false;
    private static boolean hasSynjobgroup = false;
    private static boolean hasSynjobactivity = false;
    private static boolean hasSynjobtitle = false;
    private static boolean hasSynresource = false;*/
    private static BaseBean bb = new BaseBean();
    private static String succ = "";
    private static String info = "";
    private static String way = "";

    /**
     * 初始化
     */
    public static void init() {
        DeptSynMsg = new ArrayList<>();
        SubcompanySynMsg = new ArrayList<>();
        JobGroupSynMsg = new ArrayList<>();
        JobActivitySynMsg = new ArrayList<>();
        JobTitleSynMsg = new ArrayList<>();
        ResourceSynMsg = new ArrayList<>();
        UpSupsubcomSynMsg = new ArrayList<>();//更新上级分部信息集合
        UpsubcomSynMsg = new ArrayList<>();//更新部门所属分部信息集合
        UpdSupDeptSynMsg = new ArrayList<>();//更新上级部门信息集合
        UpGroupidSynMsg = new ArrayList<>();//更新职务类型集合
        UpHrmsubcomSynMsg = new ArrayList<>();//更新人员所属分部信息集合
        UpHrmDeptSynMsg = new ArrayList<>();//更新人员所属部门信息集合
        /*hasSynsubcompany = false;
        hasSyndept = false;
        hasSynjobgroup = false;
        hasSynjobactivity = false;
        hasSynjobtitle = false;
        hasSynresource = false;*/
    }

    public void syn(String id){
        bb.writeLog("【syn方法初始化init开始】，id="+id);
        init();
        bb.writeLog("【syn方法初始化init结束】");
        if(id.equals("0")){//全部
            bb.writeLog("执行全部---------");
            SynSubcompany();
            SynDepartment();
            SynJobGroup();
            SynJobActivity();
            SynJobTitle();
            SynResource();
        }else if(id.equals("1")){//分部
            bb.writeLog("执行分部");
            SynSubcompany();
        }else if(id.equals("2")){//部门
            bb.writeLog("执行部门---------");
            SynDepartment();
        }else if(id.equals("3")){//职务类型
            bb.writeLog("执行职务类型---------");
            SynJobGroup();
        }else if(id.equals("4")){//职责
            bb.writeLog("执行职责---------");
            SynJobActivity();
        }else if(id.equals("5")){//岗位
            bb.writeLog("执行岗位---------");
            SynJobTitle();
        }else if(id.equals("6")){//人员
            bb.writeLog("执行人员--------");
            SynResource();
        }
            WriteLogToEcology();
    }

    /**
     * 同步分部
     */
    private static void SynSubcompany(){
        Map<String,Object> codeMap = new HashMap<>();//用于更新上级分部集合
        List<String> IntegerList = new ArrayList<>();//整型字段的结合
        IntegerList.add("supsubcomid");
        IntegerList.add("creater");
        IntegerList.add("modifier");
        IntegerList.add("showorder");
        IntegerList.add("companyid");
        try {
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            String sql = "select id,subcompanyname,subcompanydesc,supsubcomid,showorder," +
                    "canceled,subcompanycode from hrmsubcompany";
            rsd.execute(sql);
            String lastSyncId = "";
            int num = 0;
            int count = rsd.getCounts();
            int modifier = 1;
            int creater = 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String,Object> fieldsMap;
            while(rsd.next()){
                ++num;
                if(count == 0 || count == num){//没有数据或者结束
                    lastSyncId = "-1";
                }
                fieldsMap = new HashMap<>();
                String oldId = Util.null2String(rsd.getString("id"));
                String subcompanyname = Util.null2String(rsd.getString("subcompanyname"));
                String subcompanydesc = Util.null2String(rsd.getString("subcompanydesc"));
                String canceled = Util.null2String(rsd.getString("canceled"));
                String subcompanycode = Util.null2String(rsd.getString("subcompanycode"));
                int supsubcomid = Util.getIntValue(rsd.getString("supsubcomid"));
                int showorder = Util.getIntValue(rsd.getString("showorder"));
                if(!"".equals(subcompanyname)){
                    fieldsMap.put("subcompanyname",subcompanyname);
                }
                if(!"".equals(subcompanydesc)){
                    fieldsMap.put("subcompanydesc",subcompanydesc);
                }
                if(!"".equals(canceled)){
                    fieldsMap.put("canceled",canceled);
                }
                fieldsMap.put("outkey",oldId);
                if(showorder > -1){
                    fieldsMap.put("showorder",showorder);
                }
                fieldsMap.put("subcompanycode",subcompanycode);
                if(supsubcomid > -1){
                    codeMap.put(oldId,supsubcomid);
                }

                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                fieldsMap.put("modifier",modifier);
                fieldsMap.put("modified",modified);

                boolean isExist = isExistSubcompany(oldId);
                if(isExist){
                    String returnStr = updateData("hrmsubcompany",fieldsMap, oldId,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{
                    fieldsMap.put("creater",creater);
                    fieldsMap.put("created",created);
                    fieldsMap.put("UUID",uuid);
                    fieldsMap.put("companyid",1);//默认公司是1
                    String returnStr = insertData("hrmsubcompany",fieldsMap,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<>();
                map.put(HRMNAME, subcompanyname);
                map.put(HRMCODE, oldId);
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                SubcompanySynMsg.add(map);
            }
            if(!"".equals(lastSyncId)){
                /*hasSynsubcompany = true;*/
                upSupSubcompany(codeMap);//更新上级分部
                try {
                    SubCompanyComInfo sc = new SubCompanyComInfo();
                    sc.removeCompanyCache();
                } catch (Exception e) {
                    bb.writeLog("【SynSubcompany方法】同步分部异常：",e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 同步部门
     */
    private static void SynDepartment(){
        Map<String,Object> codeMap = new HashMap<>();//用于更新上级部门集合
        Map<String,Object> subMap = new HashMap<>();//用于更新部门所属分部集合
        List<String> IntegerList = new ArrayList<>();//整型字段的结合
        IntegerList.add("subcompanyid1");
        IntegerList.add("showorder");
        IntegerList.add("modifier");
        IntegerList.add("creater");
        String lastSyncId = "";
        int modifier = 1;
        int creater = 1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String sql = " select id,supdepid,subcompanyid1,showorder,departmentname,departmentmark," +
                    "canceled,departmentcode from HrmDepartment ";
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            rsd.execute(sql);
            int count = rsd.getCounts();
            int num = 0;
            while(rsd.next()){
                ++num;
                if(count == 0 || num == count){
                    lastSyncId = "-1";
                }
                String oldId = Util.null2String(rsd.getString("id"));//原部门id
                int supdepid = Util.getIntValue(rsd.getString("supdepid"));
                int subcompanyid1 = Util.getIntValue(rsd.getString("subcompanyid1"));
                int showorder = Util.getIntValue(rsd.getString("showorder"));
                String departmentname = Util.null2String(rsd.getString("departmentname"));
                String departmentmark = Util.null2String(rsd.getString("departmentmark"));
                String canceled = Util.null2String(rsd.getString("canceled"));
                String departmentcode = Util.null2String(rsd.getString("departmentcode"));


                Map<String,Object> fieldsMap = new HashMap<>();//字段集合
                if(!"".equals(departmentname)){
                    fieldsMap.put("departmentmark", departmentmark);
                    fieldsMap.put("departmentname", departmentname);
                }
                if(showorder > -1){
                    fieldsMap.put("showorder", showorder);
                }
                fieldsMap.put("departmentcode", departmentcode);
                if(supdepid > -1){
                    //用于更新所有部门的上级部门
                    codeMap.put(oldId,supdepid);
                }

                if(subcompanyid1 > -1){
                    //用于更新所有部门的所属分部
                    subMap.put(oldId,subcompanyid1);
                }
                if(!"".equals(canceled)){
                    fieldsMap.put("canceled", canceled);
                }

                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                fieldsMap.put("modifier",modifier);
                fieldsMap.put("modified",modified);
                fieldsMap.put("outkey",oldId);//
                boolean existDep = isExistDep(oldId);
                if(existDep){//存在，更新
                    String returnStr = updateData("hrmdepartment",fieldsMap, oldId,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{//不存在  新增
                    fieldsMap.put("creater",creater);
                    fieldsMap.put("created",created);
                    fieldsMap.put("UUID",uuid);
                    String returnStr = insertData("hrmdepartment",fieldsMap,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<>();
                map.put(HRMNAME, departmentname);
                map.put(HRMCODE, oldId);
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                DeptSynMsg.add(map);
            }
            if(!"".equals(lastSyncId)){
                /*hasSyndept = true;*/
                upSupDep(codeMap);//更新上级部门
                upSubcompany(subMap);//更新部门所属分部
                try {
                    DepartmentComInfo dci = new DepartmentComInfo();
                    dci.removeCompanyCache();
                } catch (Exception e) {
                    bb.writeLog("【SynDepartment方法】同步部门异常："+e,e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("同步部门异常-->",e.getMessage());
        }

    }

    /**
     * 同步职务类型
     */
    private static void SynJobGroup(){
        bb.writeLog("------------------------【SynJobGroup】同步职务类型：开始-------------------------");
        try {
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            String sql = "select id,jobgroupname,jobgroupremark from hrmjobgroups ";
            rsd.execute(sql);
            int num = 0;
            int count = rsd.getCounts();
            String lastSyncId = "";
            Map<String,Object> fieldsmap;
            List<Map<String,Object>> list = new ArrayList<>();
            int modifier = 1;
            int creater = 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while(rsd.next()){
                ++num;
                if(count == 0 || num == count){
                    lastSyncId = "-1";
                }
                fieldsmap = new HashMap<>();
                String dataId = Util.null2String(rsd.getString("id"));
                String jobgroupname = Util.null2String(rsd.getString("jobgroupname"));
                String jobgroupremark = Util.null2String(rsd.getString("jobgroupremark"));
                fieldsmap.put("jobgroupname",jobgroupname);
                fieldsmap.put("jobgroupremark",jobgroupremark);
                fieldsmap.put("outkey",dataId);
                list.add(fieldsmap);
            }
            List<Map<String,Object>> listUp = new ArrayList<>();
            List<Map<String,Object>> listIn = new ArrayList<>();
            List<String> IntegerList = new ArrayList<>();
            IntegerList.add("modifier");
            IntegerList.add("creater");

            for(Map<String,Object> item : list){
                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                item.put("modifier",modifier);
                item.put("modified",modified);
                boolean isExist = isExistJobGroup(Util.null2String(item.get("outkey")));
                if(isExist){
                    String returnStr = updateData("hrmjobgroups",item,Util.null2String(item.get("outkey")),IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{
                    item.put("creater",creater);
                    item.put("created",created);
                    item.put("UUID",uuid);
                    String returnStr = insertData("hrmjobgroups",item,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<String,String>();
                map.put(HRMNAME, Util.null2String(item.get("outkey")));
                map.put(HRMCODE, Util.null2String(item.get("jobgroupremark")));
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                JobGroupSynMsg.add(map);
            }


            if(!"".equals(lastSyncId)){
                /*hasSynjobgroup = true;*/
                try {
                    JobGroupsComInfo jc = new JobGroupsComInfo();
                    jc.removeCache();
                } catch (Exception e) {
                    bb.writeLog("【SynJobGroup】同步职务类型：异常，"+e,e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        bb.writeLog("------------------------【SynJobGroup】同步职务类型：结束-------------------------");
    }

    /**
     * 同步职责
     */
    private static void SynJobActivity(){
        bb.writeLog("------------------------【SynJobactivity】同步职责：开始-------------------------");
        try {
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            String sql = "select id,jobactivitymark,jobactivityname,jobgroupid\n" +
                    "from hrmjobactivities";
            rsd.execute(sql);
            Map<String,Object> fieldsmap;
            List<Map<String,Object>> list = new ArrayList<>();
            List<String> IntegerList = new ArrayList<>();
            IntegerList.add("modifier");
            IntegerList.add("creater");
            int num = 0;
            int count = rsd.getCounts();
            int modifier = 1;
            int creater = 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastSyncId = "";//
            Map<String,String> mapUpgroupid = new HashMap<>();//更新职务类型id 集合
            while(rsd.next()){
                ++num;
                if(count == 0 || num == count){
                    lastSyncId = "-1";
                }
                fieldsmap = new HashMap<>();
                String dataId = Util.null2String(rsd.getString("id"));
                String jobgroupid = Util.null2String(rsd.getString("jobgroupid"));
                String jobactivityname = Util.null2String(rsd.getString("jobactivityname"));
                fieldsmap.put("jobactivityname",jobactivityname);
                mapUpgroupid.put(dataId,jobgroupid);
                String jobactivitymark = Util.null2String(rsd.getString("jobactivitymark"));
                fieldsmap.put("jobactivitymark",jobactivitymark);
                fieldsmap.put("outkey",dataId);


                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                fieldsmap.put("modifier",modifier);
                fieldsmap.put("modified",modified);
                boolean isExist = isExistJobActivity(dataId);
                if(isExist){
                    String returnStr = updateData("hrmjobactivities",fieldsmap,dataId,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{
                    fieldsmap.put("creater",creater);
                    fieldsmap.put("created",created);
                    fieldsmap.put("UUID",uuid);
                    String returnStr = insertData("hrmjobactivities",fieldsmap,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<String,String>();
                map.put(HRMNAME, jobactivityname);
                map.put(HRMCODE, jobactivitymark);
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                JobActivitySynMsg.add(map);
            }
            if(!"".equals(lastSyncId)){//结束
                //更新职务类型id
                /*hasSynjobactivity = true;*/
                upGroupid(mapUpgroupid);
                try {
                    JobActivitiesComInfo jc = new JobActivitiesComInfo();
                    jc.removeJobActivitiesCache();
                } catch (Exception e) {
                    bb.writeLog("【SynJobActivity】同步职责：异常，"+e,e.getMessage());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        bb.writeLog("------------------------【SynJobactivity】同步职责：结束-------------------------");
    }

    /**
     * 同步岗位
     */
    private static void SynJobTitle(){
        bb.writeLog("------------------------【SynJobTitle】同步岗位：开始-------------------------");
        try {
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            String sql = "select id,jobtitlemark,jobtitlename,jobactivityid,jobdepartmentid from hrmjobtitles ";
            rsd.execute(sql);
            Map<String,Object> fieldsmap;
            List<Map<String,Object>> list = new ArrayList<>();
            List<String> IntegerList = new ArrayList<>();
            IntegerList.add("modifier");
            IntegerList.add("creater");
            int num = 0;
            int count = rsd.getCounts();
            int modifier = 1;
            int creater = 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastSyncId = "";//
            Map<String,String> mapUpactivityid = new HashMap<>();//更新职责
            Map<String,String> mapUpdepid = new HashMap<>();//更新部门
            while(rsd.next()){
                ++num;
                if(count == 0 || num == count){
                    lastSyncId = "-1";
                }
                fieldsmap = new HashMap<>();
                String dataId = Util.null2String(rsd.getString("id"));
                String jobtitlename = Util.null2String(rsd.getString("jobtitlename"));
                String jobtitlemark = Util.null2String(rsd.getString("jobtitlemark"));
                String jobactivityid = Util.null2String(rsd.getString("jobactivityid"));
                String jobdepartmentid = Util.null2String(rsd.getString("jobdepartmentid"));
                fieldsmap.put("jobtitlename",jobtitlename);
                if(!"".equals(jobactivityid)){
                    mapUpactivityid.put(dataId,jobactivityid);
                }
                if(!"".equals(jobdepartmentid)){
                    mapUpdepid.put(dataId,jobdepartmentid);
                }
                fieldsmap.put("jobtitlemark",jobtitlemark);
                fieldsmap.put("outkey",dataId);
                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                fieldsmap.put("modifier",modifier);
                fieldsmap.put("modified",modified);
                boolean isExist = isExistJobTitle(dataId);
                if(isExist){
                    String returnStr = updateData("hrmjobtitles",fieldsmap,dataId,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{
                    fieldsmap.put("creater",creater);
                    fieldsmap.put("created",created);
                    fieldsmap.put("UUID",uuid);
                    String returnStr = insertData("hrmjobtitles",fieldsmap,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<String,String>();
                map.put(HRMNAME, jobtitlename);
                map.put(HRMCODE, jobtitlemark);
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                JobTitleSynMsg.add(map);
            }

            if(!"".equals(lastSyncId)){//结束
                /*hasSynjobtitle = true;*/
                //更新职责id
                upActivityid(mapUpactivityid);
                //更新部门id
                updepid(mapUpdepid);
                try {
                    JobTitlesComInfo jc = new JobTitlesComInfo();
                    jc.removeJobTitlesCache();
                } catch (Exception e) {
                    bb.writeLog("【SynJobTitle】同步岗位：异常"+e,e.getMessage());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        bb.writeLog("------------------------【SynJobTitle】同步岗位：结束-------------------------");
    }




    /**
     * 同步人员
     */
    private static void SynResource(){
        bb.writeLog("------------------------【SynResource方法】同步人员：开始-------------------------");
        try {
            RecordSet rs_query = new RecordSet();
            rs_query.executeQuery("select lastsyntime from uf_syn_hrm  where id = 1");
            rs_query.next();
            String lastsyntime = Util.null2String(rs_query.getString("lastsyntime"));
            if("".equals(lastsyntime)){
                lastsyntime = "2010-01-01";
            }
            Map<String,Object> depcodeMap = new HashMap<>();//人员对应部门集合
            Map<String,Object> subMap = new HashMap<>();//人员对应分部集合
            Map<String,Object> jobtitleMap = new HashMap<>();//人员对应岗位集合
            Map<String,Object> belongtoMap = new HashMap<>();//人员对应主账号集合
            Map<String,Object> manageridMap = new HashMap<>();//人员对应直接上级（managerid）集合
            String lastSyncId = "";//
            List<String> IntegerList = new ArrayList<>();
            IntegerList.add("id");
            IntegerList.add("systemlanguage");
            IntegerList.add("subcompanyid1");
            IntegerList.add("departmentid");
            IntegerList.add("status");
            IntegerList.add("seclevel");
            IntegerList.add("dsporder");
            IntegerList.add("jobtitle");
            String sql = "select id,workcode,status,dsporder,mobile,jobtitle,password,lastname,loginid,systemlanguage" +
                    ",sex,birthday,lastmoddate,createdate,jobactivitydesc,departmentid," +
                    "subcompanyid1,seclevel,accounttype,belongto,managerid from hrmresource where  lastmoddate > '"+lastsyntime+"'";
            RecordSetDataSource rsd = new RecordSetDataSource("E7");
            rsd.execute(sql);
            int num = 0;
            int count = rsd.getCounts();
            while(rsd.next()){
                ++num;
                if(count == 0 || num == count){
                    lastSyncId = "-1";
                }
                String hrmid = Util.null2String(rsd.getString("id"));
                String workcode = Util.null2String(rsd.getString("workcode"));
                String status = Util.null2String(rsd.getString("status"));
                String dsporder = Util.null2String(rsd.getString("dsporder"));
                String mobile = Util.null2String(rsd.getString("mobile"));
                String jobtitle = Util.null2String(rsd.getString("jobtitle"));
                if(!"".equals(jobtitle)){
                    jobtitleMap.put(hrmid,jobtitle);
                }
                String password = Util.null2String(rsd.getString("password"));
                String lastname = Util.null2String(rsd.getString("lastname"));
                String loginid = Util.null2String(rsd.getString("loginid"));
                String systemlanguage = Util.null2String(rsd.getString("systemlanguage"));
                String sex = Util.null2String(rsd.getString("sex"));
                String birthday = Util.null2String(rsd.getString("birthday"));
                String lastmoddate = Util.null2String(rsd.getString("lastmoddate"));
                String createdate = Util.null2String(rsd.getString("createdate"));
                String jobactivitydesc = Util.null2String(rsd.getString("jobactivitydesc"));
                int departmentid = Util.getIntValue(rsd.getString("departmentid"));
                int subcompanyid1 = Util.getIntValue(rsd.getString("subcompanyid1"));
                String seclevel = Util.null2String(rsd.getString("seclevel"));
                String accounttype = Util.null2String(rsd.getString("accounttype"));
                int belongto = Util.getIntValue(rsd.getString("belongto"));
                String managerid = Util.null2String(rsd.getString("managerid"));
                if(departmentid > -1){
                    depcodeMap.put(hrmid, departmentid);
                }
                if(subcompanyid1 > -1){
                    subMap.put(hrmid,subcompanyid1);
                }
                if(!"".equals(managerid)){
                    manageridMap.put(hrmid,managerid);
                }
                if(belongto > -1){
                    belongtoMap.put(hrmid,belongto);
                }

                Map<String,Object> fieldsMap = new HashMap<>();//字段集合
                fieldsMap.put("outkey", hrmid);
                fieldsMap.put("workcode", workcode);
                fieldsMap.put("status", status);
                fieldsMap.put("dsporder", dsporder);
                fieldsMap.put("mobile", mobile);
                fieldsMap.put("jobtitle", jobtitle);
                fieldsMap.put("managerid", managerid);
                fieldsMap.put("belongto", belongto);
                fieldsMap.put("password", password);
                fieldsMap.put("lastname", lastname);
                fieldsMap.put("loginid", loginid);
                fieldsMap.put("systemlanguage", systemlanguage);
                fieldsMap.put("sex", sex);
                fieldsMap.put("birthday", birthday);
                fieldsMap.put("lastmoddate", lastmoddate);
                fieldsMap.put("createdate", createdate);
                fieldsMap.put("jobactivitydesc", jobactivitydesc);
                fieldsMap.put("seclevel", seclevel);
                fieldsMap.put("accounttype", accounttype);
                Map<String,Object> mapnew  = new HashMap<>();
                mapnew.putAll(getRealFields(fieldsMap));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String created = sdf.format(new Date());
                String modified = created;
                String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
                mapnew.put("modifier",1);
                mapnew.put("modified",modified);
                boolean exist = isExistRes(hrmid);
                if(exist){
                    String returnStr = updateData("hrmresource", mapnew, hrmid,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "更新";
                }else{
                    RecordSet rs = new RecordSet();
                    rs.executeProc("HRMRESOURCEMAXID_GET", "");
                    rs.next();
                    int id = rs.getInt(1);
                    mapnew.put("id", id);
                    mapnew.put("creater",1);
                    mapnew.put("created",created);
                    mapnew.put("UUID",uuid);
                    //bb.writeLog("当前新增的数据ID是："+id);
                    String returnStr = insertData("hrmresource",mapnew,IntegerList);
                    if(!"".equals(returnStr) && returnStr.contains(",")){
                        String temp[] = returnStr.split(",");
                        String flag = temp[0];
                        String printSQL = temp[1];
                        if(flag.equals("true")){
                            succ = "成功";
                        }else if(flag.equals("false")){
                            succ = "失败";
                            info = "SQL出错了："+printSQL;
                        }
                    }
                    way = "新增";
                }
                Map<String,String> map = new HashMap<String,String>();
                map.put(HRMNAME, lastname);
                map.put(HRMCODE, hrmid);
                map.put(HRMTYPE, way);
                map.put(HRMSTAUS, succ);
                map.put(HRMTIME, TimeUtil.getCurrentTimeString());
                map.put(HRMMSG, info);
                ResourceSynMsg.add(map);
            }
            if(!"".equals(lastSyncId)){
                /*hasSynresource = true;*/
                upDep(depcodeMap);
                upHrmSubcompany(subMap);
                upHrmJobtitle(jobtitleMap);
                upHrmmanagerid(manageridMap);
                upHrmbelongto(belongtoMap);
                RecordSet rsUp = new RecordSet();
                SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
                lastsyntime = sdfDate.format(new Date());
                rsUp.execute("update uf_syn_hrm set lastsyntime = '" + lastsyntime + "' where id = 1");
                try {
                    ResourceComInfo rci  = new ResourceComInfo();
                    rci.removeResourceCache();
                } catch (Exception e) {
                    bb.writeLog("【SynResource方法】同步人员：异常，"+e,e);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            bb.writeLog("【SynResource方法】同步人员：异常，"+e,e.getMessage());
        }
    }

    /**
     * 记录日志
     */
    private static void WriteLogToEcology(){
        List<Map<String,String>> Msglist = new ArrayList<>();

        //分部  SubcompanySynMsg
        bb.writeLog("----------------------【WriteLogToEcology方法】执行：开始");
        try {
            Msglist = SubcompanySynMsg;
            if(Msglist.size()>0){
                bb.writeLog("分部名称                          |         分部编码                                      |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【分部】异常："+e,e);
        }

        //更新上级分部
        try {
            Msglist = UpSupsubcomSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("分部编码                          |         上级分部ID       |  同步状态       |   同步时间      |  SQL ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get("subcompanycode")+" | "+ItemMap.get("supsubcomid")+" | "+ItemMap.get("status")+" | "+ItemMap.get("time")+" | "+ItemMap.get("sql"));
            }
        } catch (Exception e) {
            bb.writeLog("【更新上级分部】异常：",e.getMessage());
        }

        //部门
        try {
            Msglist = DeptSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("部门名称                          |         部门编码                                      |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【部门】异常："+e,e);
        }


        //职务类型
        try {
            Msglist = JobGroupSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("职务类型名称                          |         职务类型全称                                      |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【职务类型】异常：",e.getMessage());
        }

        //职责
        try {
            Msglist = JobActivitySynMsg;
            if(Msglist.size()>0){
                bb.writeLog("职责名称                          |         职责全称                                      |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【职责】异常：",e.getMessage());
        }


        //岗位
        try {
            Msglist = JobTitleSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("岗位名称                          |         岗位全称                                      |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【岗位】异常：",e.getMessage());
        }

        //人员
        try {
            Msglist=ResourceSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("人员名称                          |         人员工号                                     |       同步类型           |  同步状态       |   同步时间      |  描述信息 ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap= Msglist.get(i);
                bb.writeLog(ItemMap.get(HRMNAME)+" | "+ItemMap.get(HRMCODE)+" | "+ItemMap.get(HRMTYPE)+" | "+ItemMap.get(HRMSTAUS)+" | "+ItemMap.get(HRMTIME)+" | "+ItemMap.get(HRMMSG));
            }
        } catch (Exception e) {
            bb.writeLog("【人员】异常："+e,e);
        }

        //人员所属分部 UpHrmDeptSynMsg
        try {
            Msglist=UpHrmsubcomSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("人员工号                          |         所属分部                        |  同步状态       |   同步时间      |  SQL ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap= Msglist.get(i);
                bb.writeLog(ItemMap.get("workcode")+" | "+ItemMap.get("subcompanyid1")+" | "+ItemMap.get("status")+" | "+ItemMap.get("time")+" | "+ItemMap.get("sql"));
            }
        } catch (Exception e) {
            bb.writeLog("【人员】异常："+e,e);
        }

        //人员所属部门 UpHrmDeptSynMsg
        try {
            Msglist=UpHrmDeptSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("人员工号                         |         所属部门                                 |  同步状态       |   同步时间      |  SQL ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap= Msglist.get(i);
                bb.writeLog(ItemMap.get("workcode")+" | "+ItemMap.get("departmentid")+" | "+ItemMap.get("status")+" | "+ItemMap.get("time")+" | "+ItemMap.get("sql"));
            }
        } catch (Exception e) {
            bb.writeLog("【人员】异常："+e,e);
        }


        //更新上级部门
        try {
            Msglist=UpdSupDeptSynMsg;
            if(Msglist.size()>0){
                bb.writeLog("部门编码                          |         上级部门ID       |  同步状态       |   同步时间      |  SQL ");
            }
            for(int i=0;i<Msglist.size();i++){
                Map<String,String> ItemMap = Msglist.get(i);
                bb.writeLog(ItemMap.get("departmentcode")+" | "+ItemMap.get("supdepid")+" | "+ItemMap.get("status")+" | "+ItemMap.get("time")+" | "+ItemMap.get("sql"));
            }
        } catch (Exception e) {
            bb.writeLog("【更新上级部门】异常：",e.getMessage());
        }

        bb.writeLog("----------------------【WriteLogToEcology方法】执行：结束");

    }

    /**
     * 更新职务类型id
     */
    private static void upGroupid(Map<String,String> map){
        boolean flag;
        for(Map.Entry<String,String> entry : map.entrySet()){
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(entry.getValue());
            RecordSet rs = new RecordSet();
            //取当前E9系统中同步后的职务类型id，更新到当前的职责表
            rs.executeQuery("select id from hrmjobgroups  where outkey = ?",new Object[]{values});
            if(rs.next()){
                int id = Util.getIntValue(rs.getString(1));
                if(id > 0){
                    RecordSet rsUp = new RecordSet();
                    String sql = "update hrmjobactivities set jobgroupid = " + id + " where  outkey = '"+keys+"'";
                    flag = rsUp.execute(sql);
                    if(flag){
                        succ = "成功";
                    }else{
                        succ = "失败";
                    }
                    Map<String,String> mesg = new HashMap<String,String>();
                    mesg.put("jobactivityname", keys);
                    mesg.put("jobgroupid", id+"");
                    mesg.put("status", succ);
                    mesg.put("time", TimeUtil.getCurrentTimeString());
                    mesg.put("sql",sql);
                    UpGroupidSynMsg.add(mesg);
                }
            }
        }
    }

    /**
     * 更新部门id,同步岗位表用
     */
    private static void updepid(Map<String,String> map){
        for(Map.Entry<String,String> entry : map.entrySet()){
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(entry.getValue());
            RecordSet rs = new RecordSet();
            //取当前E9系统中同步后的部门id，更新到当前的岗位表
            rs.executeQuery("select id from hrmdepartment  where outkey = ?",new Object[]{values});
            if(rs.next()){
                int id = Util.getIntValue(rs.getString(1));
                if(id > 0){
                    RecordSet rsUp = new RecordSet();
                    rsUp.execute("update hrmjobtitles set jobdepartmentid = " + id + " where  outkey = '"+keys+"'");
                }
            }
        }
    }

    /**
     * 更新职责id
     */
    private static void upActivityid(Map<String,String> map){
        for(Map.Entry<String,String> entry : map.entrySet()){
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(entry.getValue());
            RecordSet rs = new RecordSet();
            //取当前E9系统中同步后的职责id，更新到当前的岗位表
            rs.executeQuery("select id from hrmjobactivities   where outkey = ?",new Object[]{values});
            if(rs.next()){
                int id = Util.getIntValue(rs.getString(1));
                if(id > 0){
                    RecordSet rsUp = new RecordSet();
                    rsUp.execute("update hrmjobtitles set jobactivityid = " + id + " where  outkey = '"+keys+"'");
                }
            }
        }
    }

    /**
     * 更新人员所在部门
     * @param map
     */
    private static  void upDep(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        boolean flag;
        String sql  = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(getDep((Integer) entry.getValue()));
            if(!"".equals(keys)){
                sql = "update hrmresource set departmentid = '"+values+"' where outkey = '"+keys+"'";
                flag = rs.execute(sql);
                if(flag){
                    succ = "成功";
                }else{
                    succ = "失败";
                }
                Map<String,String> mesg = new HashMap<>();
                mesg.put("workcode", keys);
                mesg.put("departmentid", values);
                mesg.put("status", succ);
                mesg.put("time", TimeUtil.getCurrentTimeString());
                mesg.put("sql",sql);
                UpHrmDeptSynMsg.add(mesg);
            }
        }
    }

    /**
     * 更新人员直接上级 从 E7的人员id 查找人员workcode，再从E9找到新的人员id 更新进入人员表
     * @param map
     */
    private static void upHrmmanagerid(Map<String,Object> map){
        for(Map.Entry<String,Object> entry : map.entrySet()){
            String hrmid = Util.null2String(entry.getKey());//原来人员id
            String managerid = Util.null2String(entry.getValue());//原来直接上级人员id
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from hrmresource where outkey = ?",new Object[]{managerid});
            if(rs.next()){
                int id = Util.getIntValue(rs.getString(1));
                if(id > -1){
                    RecordSet rs_up = new RecordSet();
                    rs_up.execute("update hrmresource set managerid = "+ id + " where outkey = '"+hrmid+"'");
                }
            }
        }
    }

    /**
     * 更新人员岗位 从 E7的岗位id 查找岗位name（这里因为E7的岗位code全是空值，不能用来匹配），再从E9找到新的岗位id 更新进入人员表
     * @param map
     */
    private static void upHrmJobtitle(Map<String,Object> map){

        for(Map.Entry<String,Object> entry : map.entrySet()){
            String workcode = Util.null2String(entry.getKey());//原来人员id
            String oldjobtitle = Util.null2String(entry.getValue());//原来岗位id
            RecordSet rs = new RecordSet();
            rs.executeQuery("select id from hrmjobtitles where outkey = ?",new Object[]{oldjobtitle});
            if(rs.next()){
                int id = Util.getIntValue(rs.getString(1));
                if(id > -1){
                    RecordSet rs_up = new RecordSet();
                    rs_up.execute("update hrmresource set jobtitle = "+ id + " where outkey = '"+workcode+"'");
                }
            }
        }
    }

    /**
     * 更新人员主从账号 从 E7的人员主从账号
     * @param map
     */
    private static void upHrmbelongto(Map<String,Object> map){

        for(Map.Entry<String,Object> entry : map.entrySet()){
            String hrmid = Util.null2String(entry.getKey());//原来人员id
            String oldbelongto = Util.null2String(entry.getValue());//原来主从
            RecordSet rs = new RecordSet();
            if(!"".equals(oldbelongto) && Util.getIntValue(oldbelongto) > -1){
                rs.executeQuery("select id from hrmresource where outkey = ?",new Object[]{oldbelongto});
                if(rs.next()){
                    int id = Util.getIntValue(rs.getString(1));
                    if(id > -1){
                        RecordSet rs_up = new RecordSet();
                        rs_up.execute("update hrmresource set belongto = "+ id + " where outkey = '"+hrmid+"'");
                    }
                }
            }
        }
    }

    /**
     * 根据对方给的人员登录名判断是否存在于我方库中 默认不存在
     * @param
     * @return
     */
    private static Boolean isExistRes(String workcode){
        boolean exist = false;
        if(!"".equals(workcode)){
            String sql = "select id from hrmresource where outkey = ?";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,new Object[]{workcode});
            int count =  rs.getCounts();
            if(rs.next() && count>0){
                exist = true;
            }
        }
        return exist;
    }

    /**
     * 判断分部是否存在
     * @param subcompanycode 分部编码
     * @return
     */
    private static Boolean isExistSubcompany(String subcompanycode){
        boolean exist = false;
        if(!"".equals(subcompanycode)){
            String sql = "select id from hrmsubcompany  where outkey = ?";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,new Object[]{subcompanycode});
            int count =  rs.getCounts();
            if(rs.next() && count>0){
                exist = true;
            }
        }
        return exist;
    }


    /**
     * 根据部门编码判断是否存在
     * @param code 原部门id
     * @return true ：存在    false ：不存在
     */
    private static Boolean isExistDep(String code){
        boolean exist = false;
        if(!"".equals(code)){
            String sql = "select id from hrmdepartment where outkey = ? ";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, new Object[]{code});
            int count =  rs.getCounts();
            if(rs.next() && count > 0){
                exist = true;
            }
        }
        return exist;
    }

    /**
     * 是否存在该职务类型
     * @param jobGroupName 名称
     * @return false
     */
    private static Boolean isExistJobGroup(String jobGroupName){
        boolean exist = false;
        if(!"".equals(jobGroupName)){
            String sql = "select id from hrmjobgroups where outkey = ? ";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, new Object[]{jobGroupName});
            int count =  rs.getCounts();
            if(rs.next() && count > 0){
                exist = true;
            }
        }
        return exist;
    }

    /**
     * 是否存在该职责
     * @param jobactivityname  老系统id
     * @return false
     */
    private static Boolean isExistJobActivity(String jobactivityname){
        boolean exist = false;
        if(!"".equals(jobactivityname)){
            String sql = "select id from hrmjobactivities where outkey = ? ";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, new Object[]{jobactivityname});
            int count =  rs.getCounts();
            if(rs.next() && count > 0){
                exist = true;
            }
        }
        return exist;
    }

    /**
     * 是否存在该岗位
     * @param jobtitlename 名称
     * @return false
     */
    private static Boolean isExistJobTitle(String jobtitlename){
        boolean exist = false;
        if(!"".equals(jobtitlename)){
            String sql = "select id from hrmjobtitles  where outkey = ? ";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, new Object[]{jobtitlename});
            int count =  rs.getCounts();
            if(rs.next() && count > 0){
                exist = true;
            }
        }
        return exist;
    }

    /**
     * 更新数据
     * @param tableName 表名
     * @param map  数据集合
     * @param code 更新用唯一标识
     * @param list  整型字段名集合
     * @return
     */
    private static  String updateData(String tableName,Map<String,Object> map,String code,List<String> list){
        RecordSet rs = new RecordSet();
        List<String> dateList = new ArrayList<>();//日期字段需要转换
        dateList.add("created");
        dateList.add("modified");
        String str = "outkey";
        /*if("hrmresource".equals(tableName)){
            str = "outkey";
        }else if("hrmjobgroups".equals(tableName)){
            str = "outkey";
        }else if("hrmsubcompany".equals(tableName)){
            str = "outkey";
        }else if("hrmjobactivities".equals(tableName)){
            str = "outkey";
        }else if("hrmjobtitles".equals(tableName)){
            str = "outkey";
        }*/

        String sql = "update "+tableName+" set  ";
        String valuesStr = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String key = Util.null2String(entry.getKey());
            String value = Util.null2String(entry.getValue());
            if(list.contains(key)){
                if(valuesStr.equals("")){
                    valuesStr = key+"="+value+"";
                }else{
                    valuesStr+=","+key+"="+value+"";
                }
            }else{
                if(valuesStr.equals("")){
                    if(dateList.contains(key)){
                        valuesStr = key+"= to_date('"+value+"','YYYY-MM-DD HH24:MI:SS')";
                    }else{
                        valuesStr = key+"='"+value+"'";
                    }
                }else{
                    if(dateList.contains(key)){
                        valuesStr = key+"= to_date('"+value+"','YYYY-MM-DD HH24:MI:SS')";
                    }else{
                        valuesStr += ","+key+"= '"+value+"'";
                    }
                }
            }
        }
        sql += valuesStr + " where " + str + "='" + code + "'";

        boolean flag = rs.execute(sql);
        return flag+","+sql;
    }

    /**
     * 新增数据
     * @param tableName 表名
     * @param map 数据集合
     * @param list 整型字段集合
     * @return
     */
    private static  String insertData(String tableName, Map<String, Object> map, List<String> list){
        RecordSet rs = new RecordSet();
        String sql = "insert into  "+tableName ;
        String keyString = "";
        String valueString = "";
        List<String> dateList = new ArrayList<>();//日期字段需要转换
        dateList.add("created");
        dateList.add("modified");
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            if(keyString.equals("")){
                keyString = entry.getKey();
            }else{
                keyString += ","+entry.getKey();
            }
            if(list.contains(entry.getKey())){
                if(valueString.equals("")){
                    valueString = Util.null2String(entry.getValue());
                }else{
                    valueString += ","+entry.getValue();
                }
            }else{
                if(valueString.equals("")){
                    if(dateList.contains(entry.getKey())){//日期
                        valueString = "to_date('"+entry.getValue()+"','YYYY-MM-DD HH24:MI:SS')";
                    }else{
                        valueString = "'"+entry.getValue()+"'";
                    }
                }else{
                    if(dateList.contains(entry.getKey())){//日期
                        valueString += ","+"to_date('"+entry.getValue()+"','YYYY-MM-DD HH24:MI:SS')";
                    }else{
                        valueString += ",'"+entry.getValue()+"'";
                    }

                }
            }

        }
        sql += "("+keyString+") values("+valueString+")";
        boolean flag = rs.execute(sql);
        return flag+","+sql;
    }


    /**
     * 在所有分部都同步过后更新上级分部
     * @param
     */
    private static void upSupSubcompany(Map<String,Object> map){
        boolean flag = false;
        RecordSet rs = new RecordSet();
        String sql  = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(getSupSub((Integer) entry.getValue()));
            if(!"".equals(keys)){
                if("0".equals(keys)){//如果上级分部是
                    sql  = "update hrmsubcompany set supsubcomid = '0' where outkey = '"+keys+"'";
                }else{
                    sql  = "update hrmsubcompany set supsubcomid = '"+values + "' where outkey = '"+keys+"'";
                }
                flag = rs.execute(sql);
                if(flag){
                    succ = "成功";
                }else{
                    succ = "失败";
                }
                Map<String,String> mesg = new HashMap<>();
                mesg.put("subcompanycode", keys);
                mesg.put("supsubcomid", values);
                mesg.put("status", succ);
                mesg.put("time", TimeUtil.getCurrentTimeString());
                mesg.put("sql",sql);
                UpSupsubcomSynMsg.add(mesg);
            }
        }
    }



    /**
     * 在所有部门都同步过后更新上级部门
     * @param
     */
    private static void upSupDep(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        String sql  = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(getDep((Integer) entry.getValue()));
            if(!"".equals(keys)){
                if("0".equals(keys)){//如果上级部门是
                    sql  = "update hrmdepartment set supdepid = '0' where outkey = '"+keys+"'";
                }else{
                    sql  = "update hrmdepartment set supdepid = '"+values + "' where outkey = '"+keys+"'";
                }
                boolean flag = rs.execute(sql);
                if(flag){
                    succ = "成功";
                }else{
                    succ = "失败";
                }
                Map<String,String> mesg = new HashMap<>();
                mesg.put("departmentcode", keys);
                mesg.put("supdepid", values);
                mesg.put("status", succ);
                mesg.put("time", TimeUtil.getCurrentTimeString());
                mesg.put("sql",sql);
                UpdSupDeptSynMsg.add(mesg);
            }
        }
    }



    /**
     * 根据E7 的部门id获取E9 新的id
     * @param depCode E7 系统的部门id
     * @return
     */
    private static int getDep(int depCode){
        int depId = 0;
        if(depCode == 0){
            return depCode;
        }
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmdepartment where outkey = ? ",new Object[]{depCode});
        if(rs.next()){
            depId = Util.getIntValue(rs.getString(1));
        }
        return depId;
    }

    /**
     * 根据E7的分部id 获取E9的分部id
     * @param
     * @return
     */
    private static int getSub(int depCode){
        int depId = 0;
        if(depCode == 0){
            return depCode;
        }
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmsubcompany where outkey = ? ",new Object[]{depCode});
        if(rs.next()){
            depId = Util.getIntValue(rs.getString(1));
        }
        return depId;
    }

    /**
     * 更新部门所属分部
     * @param map
     * @return
     */
    private static void upSubcompany(Map<String,Object> map){
        RecordSet rs = new RecordSet();
        String sql  = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(getSub((Integer) entry.getValue()));
            if(!"".equals(keys)){
                sql  = "update hrmdepartment set subcompanyid1 = '"+values + "' where outkey = '"+keys+"'";
                boolean flag = rs.execute(sql);
                if(flag){
                    succ = "成功";
                }else{
                    succ = "失败";
                }
                Map<String,String> mesg = new HashMap<>();
                mesg.put("oldId", keys);
                mesg.put("subcompanyid1", values);
                mesg.put("status", succ);
                mesg.put("time", TimeUtil.getCurrentTimeString());
                mesg.put("sql",sql);
                UpsubcomSynMsg.add(mesg);
            }
        }
    }

    /**
     * 更新人员所属分部
     * @param map
     * @return
     */
    private static void upHrmSubcompany(Map<String,Object> map){
        boolean flag = false;
        RecordSet rs = new RecordSet();
        String sql  = "";
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String keys = Util.null2String(entry.getKey());
            String values = Util.null2String(getSub((Integer) entry.getValue()));
            if(!"".equals(keys)){
                sql  = "update hrmresource set subcompanyid1 = '"+values + "' where outkey = '"+keys+"'";
                flag = rs.execute(sql);
                if(flag){
                    succ = "成功";
                }else{
                    succ = "失败";
                }
                Map<String,String> mesg = new HashMap<>();
                mesg.put("workcode", keys);
                mesg.put("subcompanyid1", values);
                mesg.put("status", succ);
                mesg.put("time", TimeUtil.getCurrentTimeString());
                mesg.put("sql",sql);
                UpHrmsubcomSynMsg.add(mesg);
            }
        }
    }


    /**
     * 根据E7系统上级分部id 获取 E9系统的上级分部id
     * @param subcode E7 系统的上级分部id
     * @return
     */
    private static int getSupSub(int subcode){
        if(subcode == 0){
            return subcode;
        }
        int subId = 0;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from hrmsubcompany where outkey = ?",new Object[]{subcode});
        if(rs.next()){
            subId = Util.getIntValue(rs.getString(1));
        }
        return subId;
    }

    /**
     * 删除 value 为空的键值对
     * @param map
     * @return
     */
    private static Map<String,Object> getRealFields(Map<String,Object> map){
        if(map.isEmpty()){
            return map;
        }
        Iterator<String> iterator = map.keySet().iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            if(Util.null2String(map.get(key)).equals("")){
                iterator.remove();
            }
        }
        return map;
    }


    public static void main(String[] args) {

    }

}
